package com.example.binpacking.service.Impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.binpacking.mapper.FunInterviewMapper;
import com.example.binpacking.mapper.InterviewContentMapper;
import com.example.binpacking.mapper.InterviewerMapper;
import com.example.binpacking.model.*;
import com.example.binpacking.model.dto.FunInterviewDto;
import com.example.binpacking.model.wrapper.FunInterviewWrapperContent;
import com.example.binpacking.service.FunInterviewService;
import com.example.binpacking.util.DataFormatter;
import com.example.binpacking.util.NullToEmptyStringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class FunInterviewServiceImpl implements FunInterviewService {
    @Autowired
    private FunInterviewMapper funInterviewMapper;

    @Autowired
    private InterviewerMapper interviewerMapper;

    @Autowired
    private InterviewContentMapper interviewContentMapper;
    @Override
    public Result handleAction(FunInterviewDto funInterviewDto) {
        String action = funInterviewDto.getAction().toLowerCase();
        switch (action) {
            case "add":
                return handleAddAction(funInterviewDto);
            case "edit":
                return handleEditAction(funInterviewDto);
            case "see":
                return handleSeeAction(funInterviewDto);
            case "apply":
                return handleApplyAction(funInterviewDto);
            case "del":
                return handleDelAction(funInterviewDto);
            default:
                return Result.fail(200,"n", Collections.emptyList());
        }
    }

    @Override
    public Result handleAddAction(FunInterviewDto funInterviewDto) {
        Long fun = funInterviewMapper.selectBegin();
        if(fun==null){
            funInterviewMapper.insertBegin(funInterviewDto.getLoginid(),funInterviewDto.getRightid());
//            String id =funInterviewMapper.selectId(funInterviewDto.getLoginid(),funInterviewDto.getRightid());
            List<FunInterview> f = funInterviewMapper.select(funInterviewDto.getLoginid(),funInterviewDto.getRightid(),funInterviewDto.getInterviewid());
//            System.out.println(f);
            for (FunInterview interview : f) {
                switch (interview.getIscalculated()) {
                    case "0":
                        interview.setCalculatedtip("未提交");
                        break;
                    case "1":
                        interview.setCalculatedtip("已提交");
                        break;
                    case "2":
                        interview.setCalculatedtip("计算中");
                        break;
                    case "3":
                        interview.setCalculatedtip("已计算");
                        break;
                    default:
                        interview.setCalculatedtip("未知状态");
                        break;
                }
            }
            NullToEmptyStringUtil.replaceNullsWithEmptyString(f);
            Long con = interviewContentMapper.selectBegin();
            if(con==null){
                interviewContentMapper.insertBegin();
                interviewContentMapper.initializeMaxParentid();;
                interviewContentMapper.initializeMaxId();
//                List<FunInterview> interviews = funInterviewMapper.selectByRightid(funInterviewDto.getRightid());
                String interviewId = funInterviewMapper.selectByRightid(funInterviewDto.getRightid());
                List<InterviewContent> c = interviewContentMapper.content();
                for (InterviewContent content : c) {
                    content.setParentid(interviewId); // 设置 parentid 为当前 interview 的 id
                }
                NullToEmptyStringUtil.replaceNullsWithEmptyString(c);
                int j=interviewContentMapper.updateParentid();
                List<FunInterviewWrapperContent> result = DataFormatter.formatData(f,c);
                if(j!=0) {
                    return Result.success(200, "y", result);
                }
            }
        }
        int i = funInterviewMapper.insertLoginidAndrightid(funInterviewDto.getLoginid(), funInterviewDto.getRightid());
//        String id = funInterviewMapper.selectId(funInterviewDto.getLoginid(),funInterviewDto.getRightid());
        List<FunInterview> f = funInterviewMapper.select(funInterviewDto.getLoginid(),funInterviewDto.getRightid(), funInterviewDto.getInterviewid());
        for (FunInterview interview : f) {
            switch (interview.getIscalculated()) {
                case "0":
                    interview.setCalculatedtip("未提交");
                    break;
                case "1":
                    interview.setCalculatedtip("已提交");
                    break;
                case "2":
                    interview.setCalculatedtip("计算中");
                    break;
                case "3":
                    interview.setCalculatedtip("已计算");
                    break;
                default:
                    interview.setCalculatedtip("未知状态");
                    break;
            }
        }
        System.out.println(f);
        NullToEmptyStringUtil.replaceNullsWithEmptyString(f);
        if(i!=0){
            int ij =interviewContentMapper.insertIdAndOrderid();
            interviewContentMapper.initializeMaxParentid();;
            interviewContentMapper.initializeMaxId();
            String interviewId = funInterviewMapper.selectByRightid(funInterviewDto.getRightid());
            List<InterviewContent> c = interviewContentMapper.content();
            for (InterviewContent content : c) {
                content.setParentid(interviewId); // 设置 parentid 为当前 interview 的 id
            }
            NullToEmptyStringUtil.replaceNullsWithEmptyString(c);
            int j=interviewContentMapper.updateParentid();
            List<FunInterviewWrapperContent> result = DataFormatter.formatData(f,c);
            if(j!=0) {
                return Result.success(200, "y", result);
            }
        }
        return Result.fail(200,"n",Collections.emptyList());
    }

    @Override
    public Result handleEditAction(FunInterviewDto funInterviewDto) {
        int i = interviewContentMapper.updateContentById(funInterviewDto.getContentid(),funInterviewDto.getInterviewid(),funInterviewDto.getEmotiontalk()
        ,funInterviewDto.getSleeptalk(),funInterviewDto.getDiettalk(),funInterviewDto.getHealthtalk(),funInterviewDto.getSocialtalk());
        if(i==0){
            return Result.success(200,"y",Collections.emptyList());
        }else{
              List<FunInterview> f = funInterviewMapper.selectByInterviewId(funInterviewDto.getInterviewid());
            if (f.isEmpty()) {
                return Result.fail(200, "n", Collections.emptyList());
            }

            // 根据 loginid 查询 Interviewer 列表
            String loginid = funInterviewMapper.selectLoginid(funInterviewDto.getInterviewid());
            List<Interviewer> loginInterviews = interviewerMapper.selectByLoginid(loginid);

            // 假设 Interviewer 表中有一个 name 字段，我们将其赋值给 FunInterview 的 name 字段
            String newName = loginInterviews.isEmpty() ? "" : loginInterviews.get(0).getName();
            if (newName == null) {
                newName = "";
            }

            // 遍历 FunInterview 列表，设置每个对象的 name 属性
            for (FunInterview interview : f) {
                interview.setName(newName);  // 这里假设 FunInterview 类中有 setName 方法
            }


            for (FunInterview interview : f) {
                switch (interview.getIscalculated()) {
                    case "0":
                        interview.setCalculatedtip("未计算");
                        break;
                    case "1":
                        interview.setCalculatedtip("正在计算");
                        break;
                    case "2":
                        interview.setCalculatedtip("已计算");
                        break;
                    default:
                        interview.setCalculatedtip("未知状态");
                        break;
                }
            }
              List<InterviewContent> list = interviewContentMapper.selectById(funInterviewDto.getContentid());
              NullToEmptyStringUtil.replaceNullsWithEmptyString(f);
              NullToEmptyStringUtil.replaceNullsWithEmptyString(list);
              List<FunInterviewWrapperContent> result = DataFormatter.formatData(f,list);

            return Result.success(200,"y",result);
        }

    }

    @Override
    public Result handleSeeAction(FunInterviewDto funInterviewDto) {
        String loginid = funInterviewDto.getLoginid();
        int current = funInterviewDto.getCurrentpage();
        int size = funInterviewDto.getPagesize();
        // 获取分页数据
        Page<Interview> i = getByLoginidPage(loginid,current,size);
        List<Interview> interviews = i.getRecords();
//        // 格式化 interview 数据
//        List<Map<String, Object>> formattedDatai = DataFormatter.convertAndReturnMapList(interview);
//        // 获取 loginInterviews 数据
//        String interviewId = funInterviewMapper.selectInterviewId(funInterviewDto.getLoginid());
//        List<InterviewContent> interviewContents =interviewContentMapper.selectByParentid(interviewId);
////        List<Interviewer> loginInterviews = interviewerMapper.selectByLoginid(funInterviewDto.getLoginid());
////        List<Map<String, Object>> formattedLoginInterviews = DataFormatter.convertAndReturnMapList(loginInterviews);
//        List<Map<String, Object>> formattedLoginInterviews = DataFormatter.convertAndReturnMapList(interviewContents);
//        // 添加 calculatedtip 属性
//        for (Map<String, Object> map : formattedDatai) {
//            Object iscalculated = map.get("iscalculated");
//            if (iscalculated != null) {
//                switch (iscalculated.toString()) {
//                    case "0":
//                        map.put("calculatedtip", "未计算");
//                        break;
//                    case "1":
//                        map.put("calculatedtip", "正在计算");
//                        break;
//                    case "2":
//                        map.put("calculatedtip", "已计算");
//                        break;
//                    default:
//                        map.put("calculatedtip", "未知状态");
//                        break;
//                }
//            }
//        }
//
//        // 添加 name 属性
//        if (!formattedLoginInterviews.isEmpty()) {
//            Map<String, Object> loginInterviewMap = formattedLoginInterviews.get(0); // 假设查询结果中第一个条目包含所需的名称信息
//            String name = (String) loginInterviewMap.get("name"); // 获取 name 属性
//            if (name == null) {
//                name = interviewerMapper.selectNameByLoginid(funInterviewDto.getLoginid()); // 如果 name 为 null，将其设为空字符串
//            }
//            for (Map<String, Object> map : formattedDatai) {
//                map.put("name", name);
//            }
//        }
//
////        List<Interviewer> loginInterviews = interviewerMapper.selectByLoginid(funInterviewDto.getLoginid());
////        List<Map<String, Object>> formattedLoginInterviews = DataFormatter.convertAndReturnMapList(loginInterviews);
//        Map<String, Object> baseData = formattedDatai.get(0);
//        Map<String, Object> resultData = DataFormatter.formatInterviewData(baseData, formattedLoginInterviews);
//
//        return Result.success(200,"y",Collections.singletonList(resultData));
        // 处理每一条分页数据
        List<Map<String, Object>> formattedData = interviews.stream().map(interview -> {
            // 将 interview 转换为 Map
            Map<String, Object> interviewMap = DataFormatter.convertToMap(interview);

            // 添加 calculatedtip 属性
            Object iscalculated = interviewMap.get("iscalculated");
            if (iscalculated != null) {
                switch (iscalculated.toString()) {
                    case "0":
                        interviewMap.put("calculatedtip", "未提交");
                        break;
                    case "1":
                        interviewMap.put("calculatedtip", "已提交");
                        break;
                    case "2":
                        interviewMap.put("calculatedtip", "计算中");
                        break;
                    case "3":
                        interviewMap.put("calculatedtip", "已计算");
                        break;
                    default:
                        interviewMap.put("calculatedtip", "未知状态");
                        break;
                }
            }

            // 获取 interviewId 并查询 content 数据
            String interviewId = interview.getId().toString();
            List<InterviewContent> interviewContents = interviewContentMapper.selectByParentid(interviewId);
            List<Map<String, Object>> contentList = DataFormatter.convertAndReturnMapList(interviewContents);

            // 添加 content 属性
            interviewMap.put("content", contentList);

            // 添加 name 属性
            String name = interviewerMapper.selectNameByLoginid(loginid);
            if (name == null) {
                name = "";
            }
            interviewMap.put("name", name);

            return interviewMap;
        }).collect(Collectors.toList());

        return Result.success(200, "y", formattedData);

    }

    @Override
    public Result handleDelAction(FunInterviewDto funInterviewDto) {
        FunInterview fun = funInterviewMapper.selectByLoginidAndId(funInterviewDto.getLoginid(),funInterviewDto.getInterviewid());
        Map<String,Object> map = DataFormatter.formatDataByNull(fun);
        if(fun.getIsdeleted().equals("1")){
            return  Result.success(200,"n",Collections.emptyList());
        }
        int i = funInterviewMapper.deleteLoginidAndId(funInterviewDto.getLoginid(),funInterviewDto.getInterviewid());
        if(i==0){
        return Result.success(200,"y",Collections.emptyList());
        }else{

            return Result.success(200,"y",Collections.emptyList());
        }
    }

    @Override
    public Result handleApplyAction(FunInterviewDto funInterviewDto) {
        int i = funInterviewMapper.updateByIdAndLoginid(funInterviewDto.getLoginid(),funInterviewDto.getInterviewid());
        if(i!=0){
            List<FunInterview>  f = funInterviewMapper.selectByLoginidAndInterviewId(funInterviewDto.getLoginid(),funInterviewDto.getInterviewid());
            int j = interviewContentMapper.updateContentById(funInterviewDto.getContentid(),funInterviewDto.getInterviewid(),funInterviewDto.getEmotiontalk(),funInterviewDto.getSleeptalk(),funInterviewDto.getDiettalk(),funInterviewDto.getHealthtalk(),funInterviewDto.getSocialtalk());

            List<InterviewContent> interviewContents = interviewContentMapper.selectById(funInterviewDto.getContentid());

            if (f.isEmpty()) {
                return Result.fail(200, "n", Collections.emptyList());
            }

            // 根据 loginid 查询 Interviewer 列表
            String loginid = f.get(0).getLoginid();
            List<Interviewer> loginInterviews = interviewerMapper.selectByLoginid(loginid);

            // 假设 Interviewer 表中有一个 name 字段，我们将其赋值给 FunInterview 的 name 字段
            String newName = loginInterviews.isEmpty() ? "" : loginInterviews.get(0).getName();
            if (newName == null) {
                newName = "";
            }

            // 遍历 FunInterview 列表，设置每个对象的 name 属性
            for (FunInterview interview : f) {
                interview.setName(newName);  // 这里假设 FunInterview 类中有 setName 方法
            }


            for (FunInterview interview : f) {
                switch (interview.getIscalculated()) {
                    case "0":
                        interview.setCalculatedtip("未提交");
                        break;
                    case "1":
                        interview.setCalculatedtip("已提交");
                        break;
                    case "2":
                        interview.setCalculatedtip("计算中");
                        break;
                    case "3":
                        interview.setCalculatedtip("已计算");
                        break;
                    default:
                        interview.setCalculatedtip("未知状态");
                        break;
                }
            }
            NullToEmptyStringUtil.replaceNullsWithEmptyString(f);
            NullToEmptyStringUtil.replaceNullsWithEmptyString(interviewContents);
            List<FunInterviewWrapperContent> result = DataFormatter.formatData(f,interviewContents);

            return Result.success(200,"y",result);
        }else{
            return Result.success(200,"n",Collections.emptyList());
        }
//        return null;
    }

    @Override
    public Page<Interview> getByLoginidPage(String loginid, int current, int size) {
            return funInterviewMapper.selectByLoginid(new Page<>(current, size), loginid);
    }
}
